package com.qianda.qdminiapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qianda.qdminiapp.common.constant.CommonConstant;
import com.qianda.qdminiapp.common.util.DateUtils;
import com.qianda.qdminiapp.common.util.HttpsUtil;
import com.qianda.qdminiapp.config.WxpayProperties;
import com.qianda.qdminiapp.dao.account.QqdAccountDao;
import com.qianda.qdminiapp.dao.user.QqdUserDao;
import com.qianda.qdminiapp.dao.user.UserDao;
import com.qianda.qdminiapp.domain.model.account.QqdAccount;
import com.qianda.qdminiapp.domain.model.user.QqdUser;
import com.qianda.qdminiapp.domain.model.user.User;
import com.qianda.qdminiapp.security.SecurityUser;
import com.qianda.qdminiapp.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @ClassName AuthenticationServiceImpl
 * @Author cw
 * @Date 2019/8/6 15:52
 * @Version 1.0
 */
@Service
@EnableConfigurationProperties({ WxpayProperties.class })
@Transactional
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private WxpayProperties wxpayProperties;

    @Autowired
    private QqdUserDao qqdUserDao;

    @Autowired
    private QqdAccountDao qqdAccountDao;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String code) throws UsernameNotFoundException {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("appid", "wx8582ed9a1714ce49");
        params.put("grant_type", wxpayProperties.getGrant_type());
        params.put("secret", "4aa3cc9527573afea9997e8ebba083ad");
        params.put("js_code", code);
       String res = HttpsUtil.get(wxpayProperties.getWxLoginUrl(), params);

        //测试
        Map<String,String> resultMap = JSON.parseObject(res, Map.class);
        String sub_openid = resultMap.get("openid").toString();
      //  String sub_openid = "o_HrU5IKP5zvKU3lbPN1lE-B_UQ8";
        Long companyId = 1l;
        String sub_unionid = "此用户没关注公众号";
//        if (resultMap.containsKey("unionid")) {
//           //已关注公众号
//            sub_unionid = resultMap.get("unionid").toString();
//        }
        QqdUser user = saveAndUpdateUser(sub_openid, sub_unionid,null,null,companyId);
        return new SecurityUser(user.getId(), new UserDetails() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                //这里返回空集合
                return Collections.emptyList();
            }

            @Override
            public String getPassword() {
                return null;
            }

            @Override
            public String getUsername() {
                return user.getUserName();
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;//账号是否没有失效  返回true是没有失效
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;//账号是否没有被锁，返回true是没有被锁
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isEnabled() {
                return true;
            }
        },user.getPhone(),user.getUserQqb());
    }

    private QqdUser saveAndUpdateUser(String openid, String unionid,String nickName,String avatar,Long companyId){
        //  根据openid查询用户
        QueryWrapper<QqdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_open_id",openid).eq("company_id",companyId);
        QqdUser user = qqdUserDao.selectOne(queryWrapper);
        if(user == null){
           // 用户表里还未有这个微信用户的openid--用户还未注册 进行注册
           QqdUser qqdUser = new QqdUser();
            qqdUser.setUserOpenId(openid);
            qqdUser.setCompanyId(companyId);
            qqdUser.setUserUnionId(unionid);
            qqdUser.setAvatar(avatar);
            qqdUser.setNickname(nickName);
            qqdUser.setIsNewUser(CommonConstant.IsNewUser.IS_NEW_USER);
            qqdUser.setStatus(CommonConstant.Status.STATUS_NORMAL);
            qqdUser.setCreateTime(LocalDateTime.now());
            qqdUser.setUserQqb(BigDecimal.ZERO);
            qqdUserDao.insert(qqdUser);
            user = qqdUser;

            //创建账户
            QqdAccount qqdAccount = new QqdAccount();
            qqdAccount.setUserId(qqdUser.getId());
            qqdAccount.setPhone(qqdUser.getPhone());
            qqdAccount.setBalance( BigDecimal.ZERO);
            qqdAccount.setStatus(CommonConstant.Status.STATUS_NORMAL);
            qqdAccount.setCreateTime(LocalDateTime.now());
            qqdAccountDao.insert(qqdAccount);

            //账号id回填到用户表
            qqdUser.setAccountId(qqdAccount.getId());
            qqdUserDao.updateById(qqdUser);


        }else{
            //用户表里有该微信用户，进行修改
            user.setUserUnionId(unionid);
            user.setUpdateTime(LocalDateTime.now());
            qqdUserDao.updateById(user);
        }
        return user;
    }

}
